package kr.pe.johnkim.pushchat.mobile.controller;

import kr.pe.johnkim.pushchat.mobile.domain.PushChatMessage;
import kr.pe.johnkim.pushchat.mobile.domain.PushChatUser;
import kr.pe.johnkim.pushchat.mobile.service.PushChatMessageService;
import kr.pe.johnkim.pushchat.mobile.service.PushChatUserService;
import kr.pe.johnkim.pushchat.mobile.util.PushChatCommon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * PushChat 메시지 관련된 기능들을 구현한 controller class 이다.
 *
 * @author : John_Kim <cale9797@gmail.com>
 * @date : 13. 6. 12.
 */
@Controller
@RequestMapping(value = "/pushChatMessageController")
public class PushChatMessageController {

    // SLF4J Logging
    private Logger logger = LoggerFactory.getLogger(PushChatMessageController.class);

    @Autowired
    private PushChatMessageService pushChatMessageService;

    @Autowired
    private PushChatUserService pushChatUserService;

    @Autowired
    private PushChatCommon pushChatCommon;

    @Autowired
    private HttpServletRequest httpServletRequest;

    // 이미지 업로드 Directory.
    private @Value("${pushchat.upload.message.image.directory}") String uploadMessageImageDirectory;

    // 이미지 업로드 URL.
    private @Value("${pushchat.upload.message.image.url}") String uploadMessageImageUrl;

    // 썸네일 업로드 Directory.
    private @Value("${pushchat.upload.message.thumbnail.directory}") String uploadMessageThumbnailDirectory;

    // 썸네일 업로드 URL.
    private @Value("${pushchat.upload.message.thumbnail.url}") String uploadMessageThumbnailUrl;

    /**
     * 채팅방에 메시지를 등록 한다.
     * 메시지 등록에 성공하면 Push Notification 을 발송한다.
     *
     * @param pushChatMessage
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/registerMessage", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public PushChatMessage registerMessage(@RequestBody PushChatMessage pushChatMessage) throws Exception {
        logger.info("registerMessage");

        PushChatMessage result = new PushChatMessage();

        try {
            this.pushChatMessageService.registerMessage(pushChatMessage);
            result.setResult("SUCCESS");
        } catch (Exception e) {
            result.setResult("FAIL");
        }

        /*
        채팅방 메시지 등록에 성공하면 참여자들에게 Push Notification 을 발송한다.
         */
        if(("SUCCESS").equals(result.getResult())) {
            PushChatUser parameter = new PushChatUser();

            parameter.setActivateYn(pushChatMessage.getActivateYn());
            parameter.setPushChatChatIdChat(pushChatMessage.getPushChatUserPushChatChatIdChat());
            parameter.setPushChatChatOwner(pushChatMessage.getPushChatUserPushChatChatOwner());

//            List<PushChatUser> userList = this.pushChatUserService.selectUserList(parameter);
//
//            for(int i=0 ; i<userList.size() ; i++) {
//                if(("AS").equals(userList.get(i).getDeviceType())) {
//                    this.pushChatCommon.sendASMessage(userList.get(i).getRegistrationId(), "NEW_MESSAGE");
//                } else if(("IS").equals(userList.get(i).getDeviceType())) {
//                    this.pushChatCommon.testSendIPMessage(userList.get(i).getRegistrationId(), "NEW_MESSAGE");
//                }
//            }

            for(PushChatUser pushChatUser : this.pushChatUserService.selectUserList(parameter)) {
                if(("AS").equals(pushChatUser.getDeviceType())) {
                    this.pushChatCommon.sendASMessage(pushChatUser.getRegistrationId(), "NEW_MESSAGE:" + pushChatMessage.getPushChatChatIdChat() + ":" + pushChatMessage.getPushChatChatOwner());
                } else if(("IS").equals(pushChatUser.getDeviceType())) {
                    this.pushChatCommon.testSendIPMessage(pushChatUser.getRegistrationId(), "NEW_MESSAGE", pushChatMessage.getPushChatChatIdChat(), pushChatMessage.getPushChatChatOwner());
                }
            }
        }

        return result;
    }

    /**
     * 채팅방에 이미지를 등록 한다.
     *
     * 1. 이미지를 업로드 한다.
     * 2. 썸네일을 생성 한다.
     * 3. 메시지를 등록 한다.
     *
     * 이미지 등록에 성공하면 Push Notification 을 발송한다.
     *
     * @param content
     * @param fileUrl
     * @param ip
     * @param activateYn
     * @param modifyDate
     * @param registerDate
     * @param pushChatChatIdChat
     * @param pushChatChatOwner
     * @param pushChatUserIdUser
     * @param pushChatUserMemberId
     * @param pushChatUserPushChatChatIdChat
     * @param pushChatUserPushChatChatOwner
     * @param file : 이미지 파일.
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/registerMessageWithImage", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public PushChatMessage registerMessageWithImage(
            @RequestParam("content") String content,
            @RequestParam("fileUrl") String fileUrl,
            @RequestParam("ip") String ip,
            @RequestParam("activateYn") String activateYn,
            @RequestParam("modifyDate") String modifyDate,
            @RequestParam("registerDate") String registerDate,
            @RequestParam("pushChatChatIdChat") String pushChatChatIdChat,
            @RequestParam("pushChatChatOwner") String pushChatChatOwner,
            @RequestParam("pushChatUserIdUser") String pushChatUserIdUser,
            @RequestParam("pushChatUserMemberId") String pushChatUserMemberId,
            @RequestParam("pushChatUserPushChatChatIdChat") String pushChatUserPushChatChatIdChat,
            @RequestParam("pushChatUserPushChatChatOwner") String pushChatUserPushChatChatOwner,
            @RequestParam("file") MultipartFile file
    ) throws Exception {
        logger.info("registerMessageWithImage");

        PushChatMessage parameter = new PushChatMessage();

        parameter.setContent(content);
        parameter.setFileUrl(fileUrl);
        parameter.setIp(ip);
        parameter.setActivateYn(activateYn);
        parameter.setModifyDate(modifyDate);
        parameter.setRegisterDate(registerDate);
        parameter.setPushChatChatIdChat(pushChatChatIdChat);
        parameter.setPushChatChatOwner(pushChatChatOwner);
        parameter.setPushChatUserIdUser(pushChatUserIdUser);
        parameter.setPushChatUserMemberId(pushChatUserMemberId);
        parameter.setPushChatUserPushChatChatIdChat(pushChatUserPushChatChatIdChat);
        parameter.setPushChatUserPushChatChatOwner(pushChatUserPushChatChatOwner);

        logger.info("> file size : {}", file.getSize());
        logger.info("> file name : {}", file.getOriginalFilename());
        logger.info("> content   : {}", content);

        PushChatMessage result = new PushChatMessage();

        try {
            if(!file.isEmpty()) {
                // 이미지 파일 경로를 다시 세팅 한다.
                String uploadMessageImagePath = this.httpServletRequest.getSession().getServletContext().getRealPath("/") + uploadMessageImageDirectory;
                logger.info("uploadMessageImagePath : {}", uploadMessageImagePath);
                parameter.setFileUrl(uploadMessageImageUrl + file.getOriginalFilename());

                // 썸네일 파일 경로를 다시 세팅 한다.
                String uploadMessageThumbnailPath = this.httpServletRequest.getSession().getServletContext().getRealPath("/") + uploadMessageThumbnailDirectory;
                logger.info("uploadMessageThumbnailPath  : {}", uploadMessageThumbnailPath);
                parameter.setThumbnailUrl(uploadMessageThumbnailUrl + file.getOriginalFilename());

                this.pushChatMessageService.registerMessageWithImage(parameter, uploadMessageImagePath, uploadMessageThumbnailPath, file);

                result.setResult("SUCCESS");
                logger.info("success to register image.");
            } else {
                result.setResult("FAIL");
                logger.info("fail to register image.");
            }
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.error("fail to register image.");
        }

        /*
        채팅방 이미지 등록에 성공하면 참여자들에게 Push Notification 을 발송한다.
         */
        if(("SUCCESS").equals(result.getResult())) {
            PushChatUser pushParameter = new PushChatUser();

            pushParameter.setActivateYn(parameter.getActivateYn());
            pushParameter.setPushChatChatIdChat(parameter.getPushChatUserPushChatChatIdChat());
            pushParameter.setPushChatChatOwner(parameter.getPushChatUserPushChatChatOwner());

            for(PushChatUser pushChatUser : this.pushChatUserService.selectUserList(pushParameter)) {
                if(("AS").equals(pushChatUser.getDeviceType())) {
                    this.pushChatCommon.sendASMessage(pushChatUser.getRegistrationId(), "NEW_MESSAGE:" + parameter.getPushChatChatIdChat() + ":" + parameter.getPushChatChatOwner());
                } else if(("IS").equals(pushChatUser.getDeviceType())) {
                    this.pushChatCommon.testSendIPMessage(pushChatUser.getRegistrationId(), "NEW_MESSAGE", parameter.getPushChatChatIdChat(), parameter.getPushChatChatOwner());
                }
            }
        }

        return result;
    }

    /**
     * 채팅 메시지 목록을 가져 온다.
     *
     * @param pushChatMessage
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/selectMessageList", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public List<PushChatMessage> selectMessageList(@RequestBody PushChatMessage pushChatMessage) throws Exception {
        logger.info("selectMessageList");
        return this.pushChatMessageService.selectMessageList(pushChatMessage);
    }

    /**
     * 채팅방 메시지를 비활성화 한다.
     *
     * @param pushChatMessage
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateDeactivateMessage", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public PushChatMessage updateDeactivateMessage(@RequestBody PushChatMessage pushChatMessage) throws Exception {
        logger.info("updateDeactivateMessage");

        PushChatMessage result = new PushChatMessage();

        try {
            this.pushChatMessageService.updateDeactivateMessage(pushChatMessage);
            result.setResult("SUCCESS");
            logger.info("success to update deactivate message.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.error("fail to update deactivate message.");
        }

        return result;
    }
}
